import java.awt.Dimension;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextPane;


public class EditWindow extends JFrame {

	private JTextArea questionText;
	private JTextArea usersText;
	private GuiClient gui;
	private int ownerID;
	private EditWindow ew;
	
	public EditWindow(GuiClient gui) {
		super("Edit questionnaire");
		ew = this;
		this.gui = gui;
		this.gui.load();

		ownerID = Integer.parseInt(JOptionPane.showInputDialog("Type in owner ID (integer) for the questionnaire"));
		
		if(gui.getQ().getOwner()!=ownerID){
			JOptionPane.showMessageDialog(this, "You are not the owner!");
			System.exit(0);
		}
		
		setDefaultCloseOperation(DISPOSE_ON_CLOSE);
		
		setLayout(new GridBagLayout());
        GridBagConstraints c = new GridBagConstraints();
        c.ipadx = 10;
        c.ipady = 10;
        c.insets = new Insets(5,5,5,5);
        c.fill = GridBagConstraints.NONE;
		
        c.gridx = 0;
		c.gridy = 0;
		add(new JLabel("Questions"), c);
        
		questionText = new JTextArea(gui.getQ().getQuestion(0).toString());
		questionText.setPreferredSize(new Dimension(400,200));
		questionText.setLineWrap(true);
		questionText.setWrapStyleWord(true);
		JScrollPane qScroll = new JScrollPane(questionText);
		c.gridx = 0;
		c.gridy = 1;
		add(qScroll, c);
		
		c.gridx = 0;
		c.gridy = 2;
		add(new JLabel("User IDs"), c);
		
		usersText = new JTextArea();
		usersText.setPreferredSize(new Dimension(400,150));
		usersText.setLineWrap(true);
		usersText.setWrapStyleWord(true);
		JScrollPane uScroll = new JScrollPane(usersText);
		c.gridx = 0;
		c.gridy = 3;
		add(uScroll, c);
		
		JButton button = new JButton("Save");
		button.addActionListener(new ActionListener(){			
			@Override
			public void actionPerformed(ActionEvent arg0) {
				saveQuestionnaire();
				JOptionPane.showMessageDialog(ew, "Changes have been saved!");
			}
			
		});
		c.gridx = 0;
		c.gridy = 4;
		add(button, c);
		
		pack();
		setVisible(true);
		
	}
	
	public void saveQuestionnaire() {
		//Question q = new Question(questionText.getText());
		String[] s = questionText.getText().split("\n");
		String[] s2 = usersText.getText().split("\n");
		ArrayList<Question> questions = new ArrayList<Question>();
		ArrayList<Integer> users = new ArrayList<Integer>();
		for(int i=0; i<s.length; i++){
			questions.add(new Question(s[i].trim()));
		}
		for(int i=0; i<s.length; i++){
			users.add(Integer.parseInt(s2[i].trim()));
		}
		Questionnaire q = new Questionnaire(ownerID, questions, users);
		gui.save(q, gui.getFileName());
	}
}
